package com.eryos.gwt.mailmodule.server;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

import com.eryos.gwt.mailmodule.client.ReCaptchaService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class ReCaptchaServiceImpl extends RemoteServiceServlet implements ReCaptchaService {

	private static final String PRIVATE_KEY = "6Ld5OskSAAAAAEVV8jmQJkezi9XpAgEMQShM8UqS";

	public Boolean checkCaptach(String _challenge, String _response) throws IllegalArgumentException{

		String challenge = _challenge; //(String) req.getParameter("recaptcha_challenge_field");
		String response = _response;//(String) req.getParameter("recaptcha_response_field");

		if ((challenge == null) || (response == null)) {
			throw new IllegalArgumentException("Your words did not match. Please try submitting again.");
			//throw new Exception("Your words did not match. Please try submitting again.");
		}

		String remoteAddr = getThreadLocalRequest().getRemoteHost(); // localhost // req.getRemoteAddr();

		ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
		reCaptcha.setPrivateKey(PRIVATE_KEY);

		ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, response);

		if (!reCaptchaResponse.isValid())
			return false;

		return true;
	}

}